package models

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jassue/jassue-gin/global"
	"strconv"
)

type Casbin_rule struct {
	ID
	Ptype string `form:"ptype" json:"ptype" gorm:"size:128; null;comment:ptype"`
	V0    string `form:"v0" json:"V0" gorm:"size:128;null;comment:角色id"`
	V1    string `form:"v1" json:"v1" gorm:"size:128;null;comment:权限id"`
	V2    string `form:"v2" json:"v2" gorm:"size:128;null;comment:请求方式 post"`
	V3    string `form:"v3" json:"v3" gorm:"size:128;null;comment:"`
	V4    string `form:"v4" json:"v4" gorm:"size:128;null;comment:"`
	V5    string `form:"v5" json:"v5" gorm:"size:128;null;comment:"`
}

func (casbin_rule Casbin_rule) TableName() string {
	return "casbin_rule"
}

// casbin 连接初始化
func Casbin() *casbin.Enforcer {
	dbConfig := global.App.Config.Database

	if dbConfig.Database == "" {
		return nil
	}

	s := fmt.Sprintf("%s:%s@tcp(%s)/%s",
		dbConfig.UserName,
		dbConfig.Password,
		dbConfig.Host+":"+strconv.Itoa(dbConfig.Port),
		dbConfig.Database,
	)
	//fmt.Printf("%s\n", s) //
	fmt.Println("-----auth------")

	a, _ := gormadapter.NewAdapter("mysql", s, true)
	e, _ := casbin.NewEnforcer(dbConfig.Casbin_model_conf, a)

	return e
}
